'use strict'

import axios from "axios"
import qs from 'qs'


let axiosPreURl = "http://localhost:8001/"
axios.interceptors.request.use(config => {//config包含每次请求的内容
    if (localStorage.getItem('apt_token')) {
        config.headers.apiToken = `${localhostStorage.getItem('api_token')}`;
    }
    return config;
}, err => {
    return Promise.reject(err);
});
axios.interceptors.response.use(response => {
    return response
}, error => {
    return Promise.resolve(error.response)
});
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
function checkStatus(response) {
    if (response && (response.status == 200 || response.status == 304 || response.status == 400)) {
        return response;
    }
    return {
        status: -404,
        msg: '网络异常'
    }
}
function checkCode(res) {
    if (res.status === -404) {
        alert(res.msg);
    }
    if (res.data && (!res.data.success)) {
        //alert（res.data.error_msg)
    }
    return res;
}

export default {
    post(url, data) {
        return axios({
            method: 'post',
            baseURL: axiosPreURl,
            url,
            data: data,//qs.stringify(data),
            timeout: 5000,
            headers: {
                // 'X-Requested-With':'XMLHttpRequest',
                'Content-Type': 'application/json',
                // 'Content-Type': 'application/x-www-form-=urlencoded;charset=UTF-8',

            }

        }).then((response) => {
                return checkStatus(response)
            }).then(
            (res) => {
                return checkCode(res)
            })
    },
    get(url, params) {
        return axios({
            method: 'get',
            baseURL: axiosPreURl,
            url: url,
            params,
            timeout: 5000,
            headers: {
                'x-Requested-With': 'XMLHttpRequest'
            }
        }).then(
            (response) => {
                return checkStatus(response);
            }
            ).then(
            (res) => {
                return checkCode(res)
            }
            )
    }
}
